/*
 * Copyright (c) 2009 Robert Esser
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.e2ser.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import net.e2ser.component.AbstractComponent;
import net.e2ser.component.OneD;

/**
 * @author Rob Esser
 *
 */
public class XMLWriter {
  
  private int identifier = 0;
  
  private HashMap<AbstractComponent, Integer> nodeMap = new HashMap<AbstractComponent, Integer>();
  private HashMap<OneD, Integer> connectorMap = new HashMap<OneD, Integer>();
  
  private OutputStream os;

  private int indent = 0;;

  public XMLWriter(OutputStream os) {
    this.os = os;
  }
  
  public void close() throws IOException {
    os.close();
  }
  
  public void writeHeader() throws IOException {
    writeLine("<?xml version='1.0' standalone='yes'?>");
    writeLine("<!-- a Petri Net -->");
  }

  public String addElement(AbstractComponent node) {
    // add a node to the map of nodes
    if (!nodeMap.containsKey(node)) {
      nodeMap.put(node, new Integer(identifier));
      identifier++;
    }
    return getID(node);
  }
  
  public String addElement(OneD conn) {
    // add a node to the map of nodes
    if (!connectorMap.containsKey(conn)) {
      connectorMap.put(conn, new Integer(identifier));
      identifier++;
    }
    return getID(conn);
  }

  public String getID(AbstractComponent node) {
    return "N_" + nodeMap.get(node).intValue();
  }

  public String getID(OneD conn) {
    return "C_" + connectorMap.get(conn).intValue();
  }

  public void writeLine(String s) throws IOException {
    for (int i = 0; i < indent ; i++) {
      os.write("  ".getBytes());
   }
    os.write(s.getBytes());
    os.write("\n".getBytes());
    //Log.v(PNBrowser.TAG, s);
  }
  
  public void indent() {
    indent++;
  }
  
  public void detent() {
    if (indent > 0) {
      indent--;
    }
  }

}
